import React, { useState, useRef, useEffect, useMemo, useCallback } from 'react';
import { useSelector, useDispatch, history } from 'umi';
import { RadioGroup, Radio, Picture, Price, SlideBox, AffixBottom, AsyncLoading, ActionSheet, Message } from '@/design';
import Header from '@/components/Header/Header';
import { queryOrderCreate, queryCalculate } from '@/services/order';
import { isEmpty, storeOptionListMap, getUmePic, checkField } from '@/utils/common';
import ConfirmRemarkModal from './compoments/confirmRemarkModal';
import numeral from 'numeral';
import styles from './checkorder.less';

function PCheckOrder(props: React.FC) {
  const areaCodesTips: any = {
    T86: '請填寫11位有效的手機號碼',
    T886: '請填寫有效的手機號碼10碼',
    T852: '請填寫8位有效的手機號碼',
  };
  const dispatch = useDispatch();
  const { codeDetail, storeOptionList } = useSelector((state: any) => state.store);
  const { currentstore } = useSelector((state: any) => state.currentstore);

  const {  cartList } = useSelector((state: any) => state.cartList);

  const [moreProduct, setMoreProduct] = useState<boolean>(false); // 商品列表开关
  const [amountInfo, setAmountInfo] = useState<any>({});
  const [confirmRemarkVisiable, setConfirmRemarkVisiable] = useState<boolean>(false);
  const spinning = useRef<boolean>(false);

  let userInfo = localStorage.getItem('userInfo');

  // const [remark, seRemark] = useState<string>('');
  const [state, setState] = useState<any>({
    orderRemark: '',
    comsumerPhone: '',
    comsumerName: '',
    diningWay: '',
    phoneAreaCode: '886'
  })
  const { seatNum, bespeakStartTime } = useSelector((state: any) => state.order);

// 默認的堂食方式
  useEffect(()=>{
    !isEmpty(codeDetail) && setState({
      ...state,
      diningWay: codeDetail.diningWay
    });
  }, [codeDetail])

// 計算訂單的金額
  useEffect(()=>{
    if(!isEmpty(cartList)) {
      fetchCalculate()
    }
  }, [cartList])

  const handleChangeState = (value:any ,name:string) => {
    let newItem: any = {};
    if ((typeof value === 'object' && value.hasOwnProperty('target'))) {
      value = value.target.value.replace(/\s+/g, '');
    }
    newItem[name] = value;
    setState({
      ...state,
      ...newItem
    });
  }

  /* 隐藏/开启  商品列表 */
  const handleProductChange = () => {
    console.log('惦记我')
    setMoreProduct(!moreProduct);
  };

  /* 所选的菜品 */
  const chooseTasteIds = (tasteList: any) => {
    let str: any = [];
    tasteList.forEach((o: any) => {
      str.push(`${o.tasteName}`)
    })
    return str.join('/')
  }

  // 所選套餐的菜品
  const choosePackIds = (productPackages: any) => {
    let str: any = [];
    productPackages.forEach((o: any) => {
      if(!isEmpty(o.packageDetails)) {
        o.packageDetails.forEach((item: any) => {
          if(!isEmpty(item.quantity)) {
            str.push(`${item.productName}X${item.quantity}`)
          }
          if(!isEmpty(item.num)) {
            console.log(item)
            str.push(`${item.tasteName}X${item.num}`)
          }
        })
      }
    })
    return str.join('/')
  }


  /** 選擇區號 */
  const handleChangeArea = () => {
    let areaSelect = ActionSheet.show({
      list: ['886', '86', '852'],
      maskClose: true,
      renderRow: (item) => (<span>{item}</span>),
      onSelect: (phoneAreaCode) => {
        areaSelect.hide();
        handleChangeState(phoneAreaCode, 'phoneAreaCode')
      }
    })
  }

  /* 計算價格 */
  const totaGoodlNum = (item: any) => {
    const { tasteList, productPackages } = item;
    let numTotal: any = numeral(0);
    let thisAmount = numeral(item.productPrice).multiply(item.productQuantity).value();
    numTotal = numeral(numTotal || 0).add(thisAmount).value();
    if (!isEmpty(tasteList)) {
      tasteList.forEach((taste: any) => {
        let thisAmount = numeral(taste.num).multiply(taste.price).value()
        numTotal = numeral(numTotal || 0).add(thisAmount).value();
        
      })
    }
    // 套餐
    if (!isEmpty(item.productPackages)) {
      item.productPackages.forEach((productPackage: any) => {
        if (!isEmpty(productPackage.packageDetails)) {
          productPackage.packageDetails.forEach((o: any) => {
            if (!isEmpty(o.tasteList)) {
              o.tasteList.forEach((taste: any) => {
                let thisAmount = numeral(taste.num).multiply(taste.price).value();
                thisAmount = numeral(thisAmount).multiply(o.quantity).value();
                numTotal = numeral(numTotal || 0).add(thisAmount).value();
              })
            }  else {//沒有tasteList
              let thisAmount = numeral(o.adjustPrice).multiply(o.quantity).value();
              numTotal = numeral(numTotal || 0).add(thisAmount).value();
            }
          })
        }
      })
    }
    return numTotal
  }

  /* 渲染商品 */
  const RenderProduct = ({ item }: any) => {
    // console.log(item)
    return <div className={styles.product_item}>
      <Picture className={styles.pic} src={getUmePic(item.productIcon)} />
      <div className={styles.info}>
        {/* 商品信息 */}
        <div className={styles.goods_info}>
          <h3 className={styles.name}>{item.productName}</h3>
          <p className={styles.spec}>
            <span>X {item.productQuantity}</span>
            {!isEmpty(item.tasteList) && <span className={styles.spec_num}>{chooseTasteIds(item.tasteList)}</span>}
            {!isEmpty(item.productPackages) && <span className={styles.spec_num}>{choosePackIds(item.productPackages)}</span>}

          </p>
        </div>
        {/* 價格信息 */}
        <div className={styles.price_info}>
          <Price price={totaGoodlNum(item)} />
        </div>
      </div>
    </div>
  }

  const submitOrderList = () => {
    let newCartList = JSON.parse(JSON.stringify(cartList));
    newCartList = newCartList.map((item: any) => {
      let json = item;
      if (!isEmpty(json.tasteList)) {
        json.tasteList = json.tasteList.map((o: any) => {
          return {
            tasteItemNumber: o.num,
            braId: o.braId,
            tasteId: o.tasteId,
            createTime: o.createTime,
            formatCreateTime: o.formatCreateTime,
            price: o.price,
            tasteCategoryId: o.tasteCategoryId,
            tasteItemId: o.tasteItemId,
            tasteName: o.tasteName,
          }
        })
      }
      return json
    })
    return newCartList
  }

  // 接口計算價格
  
  const fetchCalculate = async () => {
    let result = await queryCalculate(getParam());
    if (!result || !result.data) return false;
    setAmountInfo(result.data);
  }

  const getParam = () => {
    const token = localStorage.getItem('TOKEN');
    const codeId = localStorage.getItem('CODEID');
    let orderItemList = submitOrderList()
    const { tableId } = codeDetail;
    const { userId = '' } = JSON.parse(userInfo || '{}');
    let params: any = {
      buyerCode: token,
      diningWay: state.diningWay,
      operatorCode: token,
      orderItemList,
      orderRemark: state.orderRemark,
      codeId,
      seatNum,
      userId
    };
    if( storeOptionListMap(storeOptionList).get('is_first_eat') === '1') {
      params.isFirstEat = 1;
    }
    if (isTogoBespeak()) {
      const orderTime = new Date();
      orderTime.setHours(
        Number((localStorage.getItem("orderPreTime") || "00:00").split(":")[0]),
      );
      orderTime.setMinutes(
        Number((localStorage.getItem("orderPreTime") || "00:00").split(":")[1]),
      );
      params.bespeakStartTime = orderTime.valueOf();
      params.takeMealTime = bespeakStartTime;
      params.diningWay = 'togoBespeak';
    }
      params.comsumerPhone = state.comsumerPhone;
      params.comsumerName = state.comsumerName;
    return params
  }

  const fetchOrderCreate = async () => {
    if(isTogoBespeak()) {
      let checkPhone = checkField(`phone_${state.phoneAreaCode}`, state.comsumerPhone);
      if (checkPhone) {
        Message.error(checkPhone);
        return false
      };
      // if(isEmpty(state.comsumerPhone)) {
      //   return Message.error('請輸入正確手機號')
      // }
    }
    if (spinning.current) {
      return false;
    }
    spinning.current = true;
    let result = await queryOrderCreate(getParam());
    if (!isEmpty(result.data)) {
      clearCartList();
      clearSeatNum();
      history.replace(`/orderdetail?orderNo=${result.data}`);
    }
    spinning.current = false;
  }

  //下單
  const handleCreateOrder = async () => {
    if(isTogoBespeak()) {
      setConfirmRemarkVisiable(true);
      return
    }
    fetchOrderCreate();
  }

  //清空購物車
  const clearCartList = () => {
    dispatch({
      type: 'cartList/clearCartList',
      payload: []
    })
  }

  //清空購物車
  const clearSeatNum = () => {
    dispatch({
      type: 'order/saveSeatNum',
      payload: 1
    })
  }

  //是否是預約外帶
  const isTogoBespeak = () => {
    const { diningWay } = codeDetail;
    return diningWay === 'togoBespeak';
  }

  //是否是外帶
  const isTakeout = () => {//是否是預約外帶和到點外帶
    const { diningWay } = codeDetail;
    return diningWay === 'takeout' || diningWay === 'togoBespeak' || diningWay === 'togo' || diningWay === 'togoCash';
  }

  const renderProduct = useCallback(() => {
    return <div className={styles.order_products}>
    <h2 className={styles.title}>{currentstore?.braName}</h2>
    {cartList.length > 2
      ? cartList.slice(0, 2).map((item: any, index: number) => <RenderProduct key={`${item.productId}_${index}`} item={item} />)
      : cartList.map((item: any, index: number) => <RenderProduct key={`${item.productId}_${index}`} item={item} />)
    }
    {!isEmpty(cartList) && <div className={styles.content}>
      {cartList.length > 2 && <>
        <SlideBox isShow={moreProduct}>
          {cartList.slice(2).map((item: any, index: number) => <RenderProduct key={`${item.productId}_${index}`} item={item} />)}
        </SlideBox>
        <div className={styles.hideControl} onClick={handleProductChange}>
          <span>{moreProduct ? '收起' : `共 ${cartList.length} 件`}</span>
          <i className={moreProduct ? styles.active : ''}></i>
        </div>
      </>}
    </div>}
  </div>
  }, [cartList, moreProduct])

  console.log('checkorder', state)

  return <>
  {isEmpty(amountInfo) ? <AsyncLoading/> : <div className={styles.checkorder_wrap}>
    <Header hasBack title={currentstore?.braName}></Header>
    <div className={styles.table_code}>桌台號:{codeDetail?.tableCode}</div>
    {/* 商品信息 */}
    {renderProduct()}
     {!isEmpty(amountInfo) && <div className={styles.order_payment}>
      <div className={`${styles.info_item}`}>
        <label>小計</label>
        <strong><Price price={amountInfo.orderTotalSourceAmount} /></strong>
      </div>
      {!isTakeout() ? <>
        {amountInfo.serveAmount > 0 && <div className={`${styles.info_item}`}>
          <label>服務費</label>
          <strong><Price price={amountInfo.serveAmount} /></strong>
        </div>}
        {amountInfo.seatAmount > 0 && <div className={`${styles.info_item}`}>
          <label>餐位費</label>
          <strong><Price price={amountInfo.seatAmount} /></strong>
        </div>}
        {<div className={styles.need_pay}>
          <i>應付款</i>
          <Price price={amountInfo.appOrderAmount} />
        </div>}
      </> : null}
    </div>}


    {/*就餐方式  */}
    {!isTakeout() ? <div className={styles.eating_way}>
      <div className={`${styles.info_item}`}>
        <label>就餐方式</label>
        <span>
          <RadioGroup defaultValue={state.diningWay} onChange={(e: any) => { handleChangeState(e, 'diningWay') }}>
            <Radio className={styles.rt_mg} name="diningWay" value="takeout">外帶</Radio>
            <Radio name="diningWay" value="diningroom" >內用</Radio>
          </RadioGroup>
        </span>
      </div>
      <div className={`${styles.remark_item}`}>
        <label>備註</label>
        <span className={styles.remark}>
          <input onChange={e => { handleChangeState(e, 'orderRemark') }} placeholder='填寫備註' />
        </span>
      </div>
    </div> : <>
        <div className={styles.eating_way}>
          <div className={`${styles.remark_item}`}>
            <label>取餐姓名</label>
            <span className={styles.remark}>
              <input onChange={e => { handleChangeState(e, 'comsumerName') }} placeholder='請留下你的姓名方便取餐' defaultValue={state.comsumerName} />
            </span>
          </div>
          <div className={`${styles.remark_item}`}>
            <label>聯絡電話</label>
            <span className={styles.phone}>
              <button className={styles.area_code} type="button" onClick={handleChangeArea}>{state.phoneAreaCode}</button>
              <input onChange={e => { handleChangeState(e, 'comsumerPhone') }} placeholder={areaCodesTips[`T${state.phoneAreaCode}`]} defaultValue={state.comsumerPhone}/>
            </span>
          </div>
          {isTogoBespeak() && <div className={`${styles.remark_item}`}>
            <label>預約時間</label>
            <span className={styles.remark}>
              <input defaultValue={bespeakStartTime} onChange={e => { handleChangeState(e, 'comsumerPhone') }} placeholder='填寫預約時間' />
            </span>
          </div>}
          <div className={`${styles.remark_item}`}>
            <label>訂單備註</label>
            <span className={styles.remark}>
              <input onChange={e => { handleChangeState(e, 'orderRemark') }} placeholder='填寫備註' defaultValue={state.orderRemark} />
            </span>
          </div>
        </div>
      </>}
      
    {<div className={styles.pay_wrap}>
      <div className={styles.pay_hidden}></div>
      <AffixBottom className={styles.pay_main}>
        {<strong className={styles.real_amount}><Price price={amountInfo.orderAmount} /></strong>}
        <button type="button" className={styles.pay_button} onClick={handleCreateOrder}>提交訂單</button>
      </AffixBottom>
    </div>}
    <ConfirmRemarkModal
      confirmRemarkVisiable={confirmRemarkVisiable}
      onClose={() => setConfirmRemarkVisiable(false)}
      formdata={state}
      onChange={handleChangeState}
      onClickArea={handleChangeArea}
      onClickSure={fetchOrderCreate}
    />
  </div>}
  
  </>
  
}

export default PCheckOrder;